import * as React from "react";
import { inject, observer } from "mobx-react";
import { Utils } from '../../../util';
import { Form, Input, Select, Button, AutoComplete, Modal, Row, Col } from 'antd';
import { WrappedFormUtils } from 'antd/lib/form/Form';
import { LoginStore } from "../../../store";
import { register, isUserCodeExist } from '../../../basicData/api'
import { dealElement } from '../../../util/util'
import '../login.less';

const FormItem = Form.Item;
const Option = Select.Option;

interface IProps {
  loginStore?: LoginStore;
  children?: AudioContextLatencyCategory;
  form: WrappedFormUtils;
}

interface State {
  confirmDirty: boolean,
}

//初始化state并设为只读
const initialState: State = {
  confirmDirty: false,
};

type IState = Readonly<typeof initialState>;

@inject("loginStore")
@observer
class RegisterForm extends React.Component<IProps, IState> {

  readonly state: IState = initialState;

  componentDidMount() {
    this.props.loginStore.getAllCompany();
  }

  handleSubmit = (e: React.FormEvent<any>) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err: any, values: any) => {
      if (!err) {
        delete values.confirm;
        // console.log('注册 value: ', values);
        const param = dealElement(values)
        register(param).then((res: any) => {
          if (res.success) {
            Modal.success({
              title: '注册成功',
              content: '你已经注册成功，联系管理员进行审核',
              okText: '确定',
              onOk: this.login
            });
          }
        })
      }
    });
  }

  handleConfirmBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  validateToNextPassword = (rule: object, value: string, callback: Function) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  compareToFirstPassword = (rule: object, value: string, callback: Function) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不一致！');
    } else {
      callback();
    }
  }

  login = () => {
    this.props.loginStore.register(false)
  }

  //验证手机号
  checkAccount(rule: string, value: string, callback: any) {
    const regex = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (value) {
      if (regex.test(value)) {
        callback();
      } else {
        callback('手机号码格式不正确');
      }
    } else {
      callback();
    }
  }

  checkCode = (e: any) => {
    const code = e.target.value
    isUserCodeExist(code).then((res: any) => {
      if(res.result){
        Modal.error({
          content: '用户编码已存在，请重新输入',
          okText: '确定'
        })
      }
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { allCompany } = this.props.loginStore;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    // const prefixSelector = getFieldDecorator('prefix', {
    //   initialValue: '86',
    // })(
    //   <Select style={{ width: 70 }}>
    //     <Option value="86">+86</Option>
    //   </Select>
    // );

    return (
      <Form className="register-form" onSubmit={this.handleSubmit}>
        <h2>注册新用户</h2>
        <Row>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="用户编码"
            >
              {getFieldDecorator('userCode', {
                rules: [
                  { required: true, message: '请输入用户编码!', whitespace: true },
                ],
              })(
                <Input id="userCode" placeholder="请输入用户编码" onBlur={this.checkCode}/>
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="用户名称"
            >
              {getFieldDecorator('userName', {
                rules: [{ required: true, message: '请输入用户名!', whitespace: true }],
              })(
                <Input placeholder="请输入用户名" />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="真实姓名"
            >
              {getFieldDecorator('userRealName')(
                <Input placeholder="请输入用户真实姓名" />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="性别"
            >
              {getFieldDecorator('gender')(
                <Select style={{ width: '100%' }}
                  placeholder="请选择性别"
                // onChange={handleChange}
                >
                  <Option value='男' >男</Option>
                  <Option value='女' >女</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="密 码"
            >
              {getFieldDecorator('password', {
                rules: [{
                  required: true, message: '请输入密码!',
                }, {
                  validator: this.validateToNextPassword,
                }],
              })(
                <Input type="password" placeholder="请输入密码" />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="确认密码"
            >
              {getFieldDecorator('confirm', {
                rules: [{
                  required: true, message: '请确认密码!',
                }, {
                  validator: this.compareToFirstPassword,
                }],
              })(
                <Input type="password" onBlur={this.handleConfirmBlur} placeholder="请确认密码"/>
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="所属公司"
            >
              {getFieldDecorator('subordinateCompanyId', {
                rules: [{
                  type: 'number', required: true, message: '请选择所属公司!',
                }],
              })(
                <Select
                  placeholder="请选择用户所属公司"
                >
                  {
                    allCompany && allCompany.map((item: { id: number, name: string, [propName: string]: any; }, index: any) => {
                      return <Option value={item.id} key={index}>{item.name}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="联系方式"
            >
              {getFieldDecorator('telNumber', {
                rules: [{
                  type: 'string', required: false, message: '请输入联系方式!'
                }, {
                  validator: this.checkAccount,
                }],
              })(
                <Input
                  placeholder="请输入联系方式"
                />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="电子邮箱"
            >
              {getFieldDecorator('email')(
                <Input placeholder="请输入电子邮箱" />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="地址"
            >
              {getFieldDecorator('address')(
                <Input
                  placeholder="请输入地址"
                />
              )}
            </FormItem>
          </Col>
          <Col span={12} xs={24}>
            <FormItem
              {...formItemLayout}
              label="留言"
            >
              {getFieldDecorator('userRemarks')(
                <Input
                  placeholder="有什么要说的，可以留言哟!"
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <FormItem>
          {/* <Button type="primary" htmlType="submit">注册</Button>
          <a className="register-form-login" onClick={this.login}> 返回登录 </a> */}
          <Button type="primary" htmlType="submit" className="login-form-button">
            注册
          </Button>
          <span>已经有账号了？<a onClick={this.login}>立即登录</a>吧</span>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create()(RegisterForm)